<?php

declare(strict_types=1);

namespace App\Logic\Exam;

use App\Logic\BaseUserService;
use App\Model\User\Exam\UserCollection;
use App\Model\User\Exam\UserCollectionCollectionHistory;
use App\Model\User\Exam\UserCollectionSubmitUserHistory;
use App\Model\User\Exam\UserJude;
use App\Model\User\Exam\UserOption;
use App\Model\User\Exam\UserReading;
use Closure;
use Illuminate\Support\Facades\DB;

/**
 * @project: 兔兔考试系统
 * @author: Mandy
 * @date: 2023/7/19
 * @link: https://www.tutudati.com/
 * @site: 微信搜索-兔兔考试系统
 */
class CollectionService extends BaseUserService
{
    private function searchWhere(): Closure
    {
        return function ($query) {
            $requestParams = request()->all();
            $query->where("is_show", "=", 1);
            if (!empty($requestParams["category_uid"])) {
                $query->where("category_uid", "=", $requestParams["category_uid"]);
            }
            if (!empty($requestParams["recommend"])) {
                $query->where("recommend", "=", $requestParams["recommend"]);
            }
            if (!empty($requestParams["title"])) {
                $query->where("title", "like", "%{$requestParams['title']}%");
            }
            if (empty($requestParams["recommend"]) && empty($requestParams["hot"])) {
                $query->orderByDesc("sort");
            }
        };
    }

    public function getList(): array
    {
        $requestParams = request()->all();
        $buildSql = UserCollection::query()
            ->with(["category:uid,title"])
            ->where($this->searchWhere());
        if (!empty($requestParams["hot"])) {// 根据答题数量排序
            $buildSql->orderByDesc("submit");
        }
        $items = $buildSql->orderByDesc("sort")
            ->orderByDesc("id")
            ->select(["uid", "url", "path", "title", "time", "collect", "submit", "category_uid", "level", "author", "remark"])
            ->paginate($requestParams["size"] ?? 20);

        return [
            "items" => $items->items(),
            "page" => $items->currentPage(),
            "size" => $items->perPage(),
            "total" => $items->total(),
        ];
    }

    public function getRelList(): array
    {
        $requestParams = request()->all();
        if (!empty($requestParams["uid"]) || !empty($requestParams["collection_uid"])) {
            if (!empty($requestParams["uid"])) {// 根据阅读题，查询相关的试卷
                $bean = UserReading::query()
                    ->where("uid", "=", $requestParams["uid"])
                    ->first(["category_uid"]);
            } else if (!empty($requestParams["collection_uid"])) {// 根据试卷，查询相关的试卷
                $bean = UserCollection::query()
                    ->where("uid", "=", $requestParams["collection_uid"])
                    ->first(["category_uid"]);
            }
            if (!empty($bean)) {
                $bean = $bean->toArray();
                $categoryUid = $bean["category_uid"];
                return UserCollection::query()
                    ->with(["category:uid,title"])
                    ->where("category_uid", "=", $categoryUid)
                    ->where("recommend", "=", 1)
                    ->select(["uid", "url", "path", "title", "time", "collect", "submit", "category_uid", "level", "author", "remark"])
                    ->orderByDesc("sort")
                    ->orderByDesc("id")
                    ->paginate(20)
                    ->items();
            }
        }
        return [];
    }

    // 获取试卷详情
    public function content(): array
    {
        $requestParams = request()->all();
        $bean = UserCollection::query()
            ->with(["category:uid,title"])
            ->where("uid", "=", $requestParams["uid"])
            ->where("is_show", "=", 1)
            ->first(["content", "year", "uid", "url", "path", "title", "time", "collect", "submit", "category_uid", "level", "author", "remark", "picture"]);
        // 查询单选、多选和判断题数量
        if (!empty($bean)) {
            $bean = $bean->toArray();
            $bean["option_count"] = DB::table("ex_collection_option_rel")
                ->join("ex_option", "ex_collection_option_rel.exam_uid", "=", "ex_option.uid")
                ->where([
                    ["ex_collection_option_rel.collection_uid", "=", $requestParams["uid"]],
                    ["ex_option.is_show", "=", 1],
                    ["ex_option.type", "=", 1]
                ])
                ->count();
            $bean["multi_count"] = DB::table("ex_collection_option_rel")
                ->join("ex_option", "ex_collection_option_rel.exam_uid", "=", "ex_option.uid")
                ->where([
                    ["ex_collection_option_rel.collection_uid", "=", $requestParams["uid"]],
                    ["ex_option.is_show", "=", 1],
                    ["ex_option.type", "=", 2]
                ])
                ->count();
            $bean["jude_count"] = DB::table("ex_collection_jude_rel")
                ->join("ex_jude", "ex_collection_jude_rel.exam_uid", "=", "ex_jude.uid")
                ->where([
                    ["ex_collection_jude_rel.collection_uid", "=", $requestParams["uid"]],
                    ["ex_jude.is_show", "=", 1]
                ])
                ->count();
            // 获取试题总分数
            $bean["jude_score"] = (float)DB::table("ex_collection_jude_rel")
                ->join("ex_jude", "ex_collection_jude_rel.exam_uid", "=", "ex_jude.uid")
                ->where("ex_collection_jude_rel.collection_uid", "=", $requestParams["uid"])
                ->sum("ex_jude.score");
            $bean["option_score"] = (float)DB::table("ex_collection_option_rel")
                ->join("ex_option", "ex_collection_option_rel.exam_uid", "=", "ex_option.uid")
                ->where("ex_collection_option_rel.collection_uid", "=", $requestParams["uid"])
                ->sum("ex_option.score");
        } else {
            $bean = [];
        }
        return $bean;
    }

    public function submitGroupList(): array
    {
        $requestParams = request()->all();
        $collectionInfo = UserCollection::query()
            ->where("uid", "=", $requestParams["uid"])
            ->first(["submit", "collect"]);
        $items = UserCollectionSubmitUserHistory::query()
            ->with(["user:nickname,avatar_url,uid"])
            ->where([
                ["collection_uid", "=", $requestParams["uid"]]
            ])->paginate(6, ["user_uid"]);
        $isSubmit = $isCollection = 0;
        if (!empty($this->getUserUid())) {
            $submitHistory = UserCollectionSubmitUserHistory::query()->where([
                ["user_uid", "=", $this->getUserUid()],
                ["collection_uid", "=", $requestParams["uid"]]
            ])->first(["id"]);
            $collectionHistory = UserCollectionCollectionHistory::query()->where([
                ["user_uid", "=", $this->getUserUid()],
                ["collection_uid", "=", $requestParams["uid"]]
            ])->first(["id"]);
            if (!empty($submitHistory)) {
                $isSubmit = 1;
            }
            if (!empty($collectionHistory)) {
                $isCollection = 1;
            }
        }
        return [
            "list" => $items->items(),// 答题列表
            "count" => $items->total(),// 答题总人数
            "submit" => $collectionInfo["submit"],// 答题总人数
            "collect" => $collectionInfo["collect"],// 收藏总数
            "is_submit" => $isSubmit == 1,// 是否答题
            "is_collection" => $isCollection == 1,// 是否收藏
        ];
    }

    // 获取试卷套题
    public function getCollectionExamList(): array
    {
        return [
            "option" => (new OptionService())->getList(),
            "jude" => (new JudeService())->getList(),
        ];
    }
}
